package nostalgia.lastfm;

import nostalgia.lastfm.model.Lfm;
import nostalgia.lastfm.model.Weeklytrackchart;
import nostalgia.SystemConfiguration;

import javax.xml.bind.JAXBException;
import java.io.FileOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.FileInputStream;
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;

public class LastfmData {
    private static final String STORE = "lfm";
    public static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MMM-dd");

    private static LastfmData instance;

    private Lfm data = new Lfm();

    // TODO: create some indexes on the charts for quicker access when there is a lot of data

    public synchronized static LastfmData getInstance() {
        if(instance == null) {
            instance = new LastfmData();
        }
        return instance;
    }

    protected LastfmData() {
        try {
            load();
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }

    public Lfm getData() {
        return data;
    }

    protected void load() throws IOException, JAXBException {
        File f = new File(SystemConfiguration.getInstsance().getUserDataDirectory(), STORE);
        if(f.exists()) {
            data = (Lfm)JaxbFactory.getContext().createUnmarshaller().unmarshal(f);
        }
    }

    public void store() throws IOException, JAXBException {
        File f = new File(SystemConfiguration.getInstsance().getUserDataDirectory(), STORE);
        JaxbFactory.getContext().createMarshaller().marshal(data, f);
    }

    public static Date getDateFromChart(long value) {
        return new Date(value * 1000);
    }

    public static void main(String[] argv) {
        System.out.println(getDateFromChart(1228046400));
        System.out.println(getDateFromChart(1228651200));
    }
}
